﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using OSMLib;
using WGS84;

namespace LaoMap
{

    /// <summary>
    ///  http://maplibrary.org/stacks/gadm/index.php
    ///  
    ///LAO.mif
    ///LAO.mid
    ///  
    /// </summary>
    class OpenMapLibrary
    {
        public readonly List<string[]> _mapNames = new List<string[]>();
        public readonly List<List<Wgs84Coordinate>> _regions = new List<List<Wgs84Coordinate>>();

        public void LoadMapLib()
        {
            LoadMid();
            LoadMif();
        }

        void LoadMid()
        {
            _mapNames.Clear();
            // Parklai,,LA.XA.PA,Xaignabouri,Parklai,Province
            const string f = @"C:\laomapdata\LAO.mid";

            using (TextReader tr = new StreamReader(f))
            {
                string line;
                while (true)
                {
                    line = tr.ReadLine();
                    if (line == null)
                        break;

                    string[] sa = line.Split(',');
                    _mapNames.Add(sa);
                }
            }
        }

        void LoadMif()
        {
            _regions.Clear();
            /*
             *            
             region 1
             688
             101.171676 18.093389
             101.171379 18.093811
             101.170990 18.094431
             101.170349 18.095231
             * 
             * */
            const string f = @"C:\laomapdata\LAO.mif";

            using (TextReader tr = new StreamReader(f))
            {
                List<Wgs84Coordinate> region = null;
                string line;
                while (true)
                {
                    line = tr.ReadLine();
                    if (line == null)
                        break;

                    if (line.StartsWith("region"))
                    {
                        region = new List<Wgs84Coordinate>();
                        _regions.Add(region);
                        continue;
                    }

                    if (region == null)
                        continue;

                    string[] fields = line.Split(' ');
                    if (fields.Count() != 2)
                        continue;

                    double lon;
                    if (!double.TryParse(fields[0], out lon))
                        continue;

                    double lat;
                    if (!double.TryParse(fields[1], out lat))
                        continue;

                    region.Add(new Wgs84Coordinate(lat, lon));

                }
            }
        }
    }
}
